let createError = require('http-errors');
let express = require('express');
let path = require('path');
let logger = require('morgan');
let multer = require('multer');
let cors = require('cors');
let history = require('connect-history-api-fallback');

// 服务器
let app = express();
app.use(history(
  {
    htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
  }
));
app.use('admin', express.static(path.join(__dirname, './public/admin')));//管理端静态资源托管 
app.use(express.static(path.join(__dirname, './public/template')));//客户端静态资源托管 
app.use(express.static(path.join(__dirname, './public')));//公共资源托管 

app.use(cors({
  //允许所有前端域名
  "origin": ["http://localhost:8001", "http://localhost:5000", "http://127.0.0.1:8848", "http://localhost:8080", "*"],
  "credentials": true,//允许携带凭证
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", //被允许的提交方式
  "allowedHeaders": ['Content-Type', 'Authorization', 'token']//被允许的post方式的请求头
}));

// view engine setup
// 后端渲染ejs配置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 安装中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

let storage = multer.diskStorage({
  // 上传文件的储存位置
  destination: function (req, file, cb) {
    if (req.url.includes("user") || req.url.includes("reg")) {
      cb(null, path.join(__dirname, 'public', 'upload', 'user'))
    } else if (req.url.includes("banner")) {
      cb(null, path.join(__dirname, 'public', 'upload', 'banner'))
    } else {
      cb(null, path.join(__dirname, 'public', 'upload', 'goods'))
    }
  }
  // 重命名
  // filename: function (req, file, cb) {
  //   cb(null, file.fieldname + '-' + Date.now())
  // }
})

let upload = multer({ storage })
// const objMulter=multer({dest:'./public/upload'})//dest: 指定 保存位置（存到服务器)
app.use(upload.any());//允许上传什么类型文件,any|text|image 代表任何类型

// 响应（路由）
// 管理端
app.use('/admin/login', require('./routes/admin/login'));
app.use('/admin/success', require('./routes/admin/feedback/success'));
app.use('/admin/error', require('./routes/admin/feedback/error'));
app.all('/admin/*', require('./routes/admin/islogin'))
app.use('/admin', require('./routes/admin/home'));
app.use('/admin/home', require('./routes/admin/home'));
app.use('/admin/goods', require('./routes/admin/goods'));
app.use('/admin/banner', require('./routes/admin/banner'));
app.use('/admin/user', require('./routes/admin/user'));

// 客户端
app.all("/api/*", require('./routes/api/params'));
app.use('/api/reg', require('./routes/api/reg'));
app.use('/api/login', require('./routes/api/login'));
app.use('/api/user', require('./routes/api/user'));
app.use('/api/goods', require('./routes/api/goods'));
app.use('/api/cart', require('./routes/api/cart.js'));
app.use('/api/banner', require('./routes/api/banner'));
// 代理端






// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  if (req.url.includes('/api')) {// 用户端接口不存在 返回  {err:1,msg:'不存在的接口'}
    res.send({ err: 1, msg: '不存在的接口' })
  } else if (req.url.includes('/admin')) {// 管理端接口不存在 返回  res.render('error.ejs')
    res.render('./feedback/error', { msg: '不存在的后台地址' });
  } else { // 资源托管没有对应的页面 返回 404.html
    res.sendFile(path.join(__dirname, 'public', 'template', 'index.html'))
  }
});

module.exports = app;
